package com.wannengbang.cloudleader.homepage;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.wannengbang.cloudleader.R;
import com.wannengbang.cloudleader.base.BaseActivity;
import com.wannengbang.cloudleader.base.DataCallBack;
import com.wannengbang.cloudleader.bean.AliAuthDataBean;
import com.wannengbang.cloudleader.bean.BaseResponseBean;
import com.wannengbang.cloudleader.bean.UserInfoBean;
import com.wannengbang.cloudleader.dialog.UpdateSettlementDialog;
import com.wannengbang.cloudleader.homepage.model.HomePageModelImpl;
import com.wannengbang.cloudleader.mine.model.MineModelImpl;
import com.wannengbang.cloudleader.pay.alipay.AliPayUtil;
import com.wannengbang.cloudleader.pay.alipay.AuthResult;
import com.wannengbang.cloudleader.utils.FastClickUtils;
import com.wannengbang.cloudleader.utils.SPManager;
import com.wannengbang.cloudleader.utils.ToastUtil;
import com.wannengbang.cloudleader.widget.AppTitleBar;
import com.wannengbang.cloudleader.widget.ViewLoading;

import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class SettlementInfoActivity extends BaseActivity {


    @BindView(R.id.ll_alipay_binding)
    LinearLayout llAlipayBinding;
    @BindView(R.id.title_bar)
    AppTitleBar titleBar;
    @BindView(R.id.tv_settle_name)
    EditText tvSettleName;
    @BindView(R.id.tv_settle_mobile)
    EditText tvSettleMobile;
    @BindView(R.id.tv_id_card)
    EditText tvIdCard;
    @BindView(R.id.tv_card_no)
    EditText tvCardNo;
    @BindView(R.id.tv_commit)
    TextView tvCommit;
    @BindView(R.id.tv_banding_name)
    TextView tvBandingName;
    private UserInfoBean userInfoBean;
    private HomePageModelImpl homePageModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settlement_info);
        ButterKnife.bind(this);
        homePageModel = new HomePageModelImpl();
        requestUserInfo();
    }


    public void requestUserInfo() {
        new MineModelImpl().requestMine(new DataCallBack<UserInfoBean>() {
            @Override
            public void onSuccessful(UserInfoBean bean) {
                userInfoBean = bean;
                SPManager.getInstance().saveUserInfoJson(new Gson().toJson(bean));
                tvSettleName.setText(bean.getData().getSettle_name());
                tvSettleMobile.setText(bean.getData().getSettle_mobile());
                tvIdCard.setText(bean.getData().getSettle_id_card());
                tvCardNo.setText(bean.getData().getSettle_card_no());

                if (!TextUtils.isEmpty(bean.getData().getSettle_name())
                        && !TextUtils.isEmpty(bean.getData().getSettle_mobile())
                        && !TextUtils.isEmpty(bean.getData().getSettle_id_card())
                        && !TextUtils.isEmpty(bean.getData().getSettle_card_no())) {

                    tvCommit.setText("修改信息");
                    tvSettleName.setEnabled(false);
                    tvSettleMobile.setEnabled(false);
                    tvIdCard.setEnabled(false);
                    tvCardNo.setEnabled(false);
                } else {
                    tvCommit.setText("提交");
                    tvSettleName.setEnabled(true);
                    tvSettleMobile.setEnabled(true);
                    tvIdCard.setEnabled(true);
                    tvCardNo.setEnabled(true);
                }

                if (TextUtils.isEmpty(bean.getData().getAlipay_user_id()) || "0".equals(bean.getData().getAlipay_user_id())) {
                    llAlipayBinding.setEnabled(true);
                    tvBandingName.setText("去绑定");
                } else {
                    llAlipayBinding.setEnabled(false);
                    tvBandingName.setText("已绑定");
                }
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }


    @OnClick({R.id.tv_commit, R.id.ll_alipay_binding})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_commit:
                if (FastClickUtils.isFastClick()) {
                    return;
                }
                if (userInfoBean == null) {
                    return;
                }
                if (!TextUtils.isEmpty(userInfoBean.getData().getSettle_name())
                        && !TextUtils.isEmpty(userInfoBean.getData().getSettle_mobile())
                        && !TextUtils.isEmpty(userInfoBean.getData().getSettle_id_card())
                        && !TextUtils.isEmpty(userInfoBean.getData().getSettle_card_no())) {

                    UpdateSettlementDialog dialog = UpdateSettlementDialog.newInstance(userInfoBean.getData().getSettle_name(),
                            userInfoBean.getData().getSettle_mobile(), userInfoBean.getData().getSettle_id_card(), userInfoBean.getData().getSettle_card_no());
                    dialog.show(getSupportFragmentManager(), "dialog");
                    dialog.setOnCallBackListener(new UpdateSettlementDialog.OnCallBackListener() {
                        @Override
                        public void onCallBack(String settleName, String settleMobile, String idCard, String cardNo) {
                            requestUserInfo();
                        }
                    });

                } else {
                    commit();
                }
                break;
            case R.id.ll_alipay_binding:
                if (FastClickUtils.isFastClick()) {
                    return;
                }
                requestAliSign();
                break;
        }
    }

    public void commit() {
        String settleName = tvSettleName.getText().toString();
        String settleMobile = tvSettleMobile.getText().toString();
        String idCard = tvIdCard.getText().toString();
        String cardNo = tvCardNo.getText().toString();

        if (TextUtils.isEmpty(settleName)) {
            ToastUtil.showShort("请输入姓名");
            return;
        }
        if (TextUtils.isEmpty(settleMobile)) {
            ToastUtil.showShort("请输入手机号");
            return;
        }
        if (TextUtils.isEmpty(idCard)) {
            ToastUtil.showShort("请输入身份证号");
            return;
        }
        if (TextUtils.isEmpty(cardNo)) {
            ToastUtil.showShort("请输入结算银行卡号");
            return;
        }
        ViewLoading.showProgress(mActivity);
        new HomePageModelImpl().requestVerifyBankFourFactor(settleName, settleMobile, idCard, cardNo, new DataCallBack<BaseResponseBean>() {
            @Override
            public void onSuccessful(BaseResponseBean bean) {
                ToastUtil.showShort("提交成功");
                finish();
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    /**
     * 获取支付宝 授权
     */
    public void requestAliSign() {
        ViewLoading.showProgress(mActivity);
        homePageModel.requestAliSign(new DataCallBack<AliAuthDataBean>() {
            @Override
            public void onSuccessful(AliAuthDataBean bean) {
                AliPayUtil.authV2(mActivity, bean.getData(), mHandler);
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    /**
     * 提交 userid
     *
     * @param alipay_user_id
     */
    public void requestAliAuth(String alipay_user_id) {
        homePageModel.requestAliAuth(alipay_user_id, new DataCallBack<BaseResponseBean>() {
            @Override
            public void onSuccessful(BaseResponseBean bean) {
                ToastUtil.showShort("绑定成功");
                llAlipayBinding.setEnabled(false);
                tvBandingName.setText("已绑定");
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 8: {
                    @SuppressWarnings("unchecked")
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();

                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
                        // 获取alipay_open_id，调支付时作为参数extern_token 的value
                        // 传入，则支付账户为该授权账户
                        requestAliAuth(authResult.getUserId());
                    } else {
                        // 其他状态值则为授权失败
                        ToastUtil.showShort("授权失败");
                    }
                    break;
                }
                default:
                    break;
            }
        }
    };
}
